package com.xingkeduo.business.operation.domain;

import com.xingkeduo.business.operation.service.*;
import com.xingkeduo.pojo.dto.ScreenPrice.ScreenPriceParm;
import com.xingkeduo.pojo.query.ScreenPriceQuery;
import com.xingkeduo.pojo.query.ShopsQuery;
import com.xingkeduo.pojo.query.ShopsServprodQuery;
import com.xingkeduo.pojo.table.ScreenPriceTable;
import com.xingkeduo.pojo.table.ShopsServprodTable;
import com.xingkeduo.pojo.table.ShopsTable;
import com.xingkeduo.pojo.vo.ScreenPriceVo;
import com.xingkeduo.tool.AmountUtils;
import com.xingkeduo.tool.MySortUtils;
import com.xingkeduo.tool.ResponseMessage;
import com.xingkeduo.tool.TimeUtil;
import com.xingkeduo.util.pojo.enums.YesNoEnum;
import com.xingkeduo.util.pojo.exception.DataException;
import com.xingkeduo.util.tool.CommonUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chenxianda <chenxianda@xingkeduo.com>
 * @package BeautyOS 2019年7月19日 11:32:47
 * @copyright Copyright (c) XKD 2019
 */

@Component
public class ScreenPriceDomain {
    @Autowired
    private ScreenPriceService screenPriceService;

    @Autowired
    private ShopsService shopsService;

    @Autowired
    private ShopsServprodService shopsServprodService;

    //根据店铺ID查询下单屏幕信息
    public ScreenPriceVo getScreenPriceInfoById(long shopId) throws Throwable {

        if(CommonUtil.isEmpty(shopId)){
            throw new DataException(DataException.Type.FAIL, "店铺ID不能为空");
        }
        ScreenPriceQuery screenPriceQuery = new ScreenPriceQuery();
        screenPriceQuery.setShopId(shopId);
        screenPriceQuery.setTime(TimeUtil.DateToFormat(new Date(), "HH:mm"));
        screenPriceQuery.setDayids(String.valueOf(TimeUtil.getWeek()));

        List<ScreenPriceTable> screenPriceTables = screenPriceService.selectScreenPrices(screenPriceQuery);
        ScreenPriceVo screenPriceVo = new ScreenPriceVo();
        if(screenPriceTables != null && screenPriceTables.size()>0){
            BeanUtils.copyProperties(screenPriceTables.get(0),screenPriceVo);
            //todo 为了以防万一查出来多条数据，那么就取最后一条数据，完美
            if(screenPriceTables.size()>1){
                for (ScreenPriceTable screenPriceTable : screenPriceTables) {
                    BeanUtils.copyProperties(screenPriceTable,screenPriceVo);
                }
            }
        }
        return screenPriceVo;
    }
    //查询下单屏幕信息
    public List<ScreenPriceVo> getScreenPriceListInfo(ScreenPriceQuery screenPriceQuery) throws Throwable {

        List<ScreenPriceVo> screenPriceVoList = new ArrayList<>();

        List<ScreenPriceTable> screenPriceTables = screenPriceService.selectScreenPrices(screenPriceQuery);

        if(screenPriceTables!=null&&screenPriceTables.size()>0){
            for (ScreenPriceTable screenPriceTable : screenPriceTables) {
                ScreenPriceVo screenPriceVo = new ScreenPriceVo();
                BeanUtils.copyProperties(screenPriceTable,screenPriceVo);
                screenPriceVoList.add(screenPriceVo);
            }
        }
        return screenPriceVoList;
    }

    //创建下单屏
    public int createScreenPrice(ScreenPriceParm screenPriceParm, Long operator) throws Throwable {

        List<ScreenPriceTable> screenPriceInfo = screenPriceParm.getScreenPriceInfo();
        if(screenPriceInfo ==null&&screenPriceInfo.size()==0){
            throw new DataException(DataException.Type.FAIL, "数据不能为空");
        }
        if(screenPriceParm.getShopId() == null){
            throw new DataException(DataException.Type.FAIL, "店铺ID不能为空");
        }

        List<ScreenPriceTable> screenPriceTables = screenPriceService.selectScreenPrices(new ScreenPriceQuery().setShopId(screenPriceParm.getShopId()));

        if(screenPriceTables!=null && screenPriceTables.size()>0){
            throw new DataException(DataException.Type.FAIL, "该店铺下单屏幕信息已存在，请前往编辑修改");
        }
        //验证时间是否重复
        checkDaysTimeCross(screenPriceInfo);
        //填充一下数据
        for (ScreenPriceTable screenPriceTable : screenPriceInfo) {
            screenPriceTable.setShopId(screenPriceParm.getShopId());
            screenPriceTable.setCreatedBy(operator);
        }
       //添加新数据
        int createRes = screenPriceService.insertAll(screenPriceInfo);
        if (createRes > 0){
            return createRes;
        }
        throw new DataException(DataException.Type.FAIL, "价格添加创建失败");
    }



    public int createScreenScript() throws Throwable {

        //初始化数据之前首先判断一下表中是否有数据，有的话全部查出来做一下假删除操作
        List<ScreenPriceTable> screenPriceTables = screenPriceService.selectScreenPrices(new ScreenPriceQuery());
        if(screenPriceTables !=null && screenPriceTables.size()>0){
            for (ScreenPriceTable screenPriceTable : screenPriceTables) {
                ScreenPriceTable screenPriceTable1 = new ScreenPriceTable();
                screenPriceTable1.setId(screenPriceTable.getId());
                screenPriceTable1.setIsDelete(YesNoEnum.YES);
                screenPriceService.update(screenPriceTable1);
            }
        }
        List<ScreenPriceTable> screenPriceInfo = new ArrayList<>();
        List<ShopsTable> shopsTableList = shopsService.selectLists(new ShopsQuery());
        //把所有的门店ID取出来
        List<Long> shopIdList = shopsTableList.stream().map(ShopsTable::getId).collect(Collectors.toList());
        //todo 看一下是不是需要去除Barber服务的价格
//        List<Long> servprodIdList = new ArrayList<>();
//        servprodIdList.add(Long.valueOf(1));
//        servprodIdList.add(Long.valueOf(2));
//        servprodIdList.add(Long.valueOf(5));
        for (Long aLong : shopIdList) {
            //获取门店配置最高库存颗粒
            List<ShopsServprodTable> shopsServprodTableList = shopsServprodService.selectLists(new ShopsServprodQuery().setShopsId(aLong));
            List<Integer> grain = new ArrayList<>();
            ScreenPriceTable screenPriceTable = new ScreenPriceTable();
            if(!CommonUtil.isEmpty(shopsServprodTableList) && shopsServprodTableList.size() > 0){
                for (ShopsServprodTable shopsServprodTable : shopsServprodTableList) {
                    grain.add(Math.toIntExact(shopsServprodTable.getPrice()));
                }
                List<Integer> integers = MySortUtils.max1(grain);
                Integer integer = integers.get(0);
                if(integers == null || integers.size() == 0){
                    screenPriceTable.setDisplayPrice(String.valueOf(0));
                }else{
                    screenPriceTable.setDisplayPrice(AmountUtils.changeF2Y1(Long.valueOf(integer)));
                }
            }else{
                screenPriceTable.setDisplayPrice(String.valueOf(0));
            }
            screenPriceTable.setShopId(aLong);
            screenPriceTable.setDayids("1,2,3,4,5,6,7");
            screenPriceTable.setStartTime("00:00");
            screenPriceTable.setEndTime("23:59");
            screenPriceTable.setCreatedBy(38);

            screenPriceInfo.add(screenPriceTable);

        }
        //添加新数据
        int createRes = screenPriceService.insertAll(screenPriceInfo);
        if (createRes > 0){
            return createRes;
        }
        throw new DataException(DataException.Type.FAIL, "价格添加创建失败");
    }








    //修改下单屏幕信息
    public ResponseMessage modifyScreenPrice(ScreenPriceParm screenPriceParm , Long operator) throws Throwable {

        List<ScreenPriceTable> screenPriceInfo = screenPriceParm.getScreenPriceInfo();
        if(screenPriceParm.getShopId() == null){
            throw new DataException(DataException.Type.FAIL, "店铺ID不能为空");
        }
        checkDaysTimeCross(screenPriceInfo);
        if(screenPriceInfo!=null && screenPriceInfo.size()>0){
            List<Long> screenPriceId = new ArrayList<>();
            for (ScreenPriceTable screenPriceTable : screenPriceInfo) {
                screenPriceTable.setShopId(screenPriceParm.getShopId());
                screenPriceTable.setCreatedBy(operator);
                screenPriceTable.setUpdatedBy(operator);
               if(CommonUtil.isEmpty(screenPriceTable.getId()) ||screenPriceTable.getId()==0){
                    //添加下单屏幕信息
                   screenPriceService.insert(screenPriceTable);
                   screenPriceId.add(screenPriceTable.getId());
               }
                if(!CommonUtil.isEmpty(screenPriceTable.getId())){
                    //修改下单屏幕信息
                    screenPriceService.update(screenPriceTable);
                    screenPriceId.add(screenPriceTable.getId());
                }
            }
            //screenPriceId这个数组中的ID和数据库中查出来的ID对比一下,不同的ID状态全部改为删除
            List<ScreenPriceVo> screenPriceListInfo = getScreenPriceListInfo(new ScreenPriceQuery().setShopId(screenPriceParm.getShopId()));
            List<Long> collect = screenPriceListInfo.stream().map(ScreenPriceVo::getId).collect(Collectors.toList());
            collect.removeAll(screenPriceId);
            List<Long> screenPriceDelList = collect;
            if(screenPriceDelList!=null&&screenPriceDelList.size()>0){
                for (Long aLong : screenPriceDelList) {
                    //这里执行一下假删除操作
                    ScreenPriceTable screenPriceTable = new ScreenPriceTable();
                    screenPriceTable.setId(aLong);
                    screenPriceTable.setIsDelete(YesNoEnum.YES);
                    screenPriceService.update(screenPriceTable);
                }
            }
            return ResponseMessage.ok();
        }
        throw new DataException(DataException.Type.FAIL, "下单屏信息修改失败");
    }

    //这里做一下验证
    protected ResponseMessage checkDaysTimeCross(List<ScreenPriceTable> screenPriceInfo) {

        if(screenPriceInfo!=null&&screenPriceInfo.size()>1)
        {
            for (int i = 0; i < screenPriceInfo.size() - 1; i++) {
                Map<String, Boolean> dayMap = new HashMap<>();// 保存当前一行数据中的days
                Date startDate = TimeUtil.formatDateHH_mm(screenPriceInfo.get(i).getStartTime());
                Date endDate = TimeUtil.formatDateHH_mm(screenPriceInfo.get(i).getEndTime());
                if(startDate.after(endDate) || startDate.equals(endDate)){
                    throw new DataException(DataException.Type.FAIL, "开始时间必须大于结束时间");
                }
                String days = screenPriceInfo.get(i).getDayids();
                String[] daysArr = days.split(",");// 假设选中的周天有值 需判空处理？
                for (int x = 0; x < daysArr.length; x++) {
                    dayMap.put(daysArr[x], true);
                }
                for (int j = i + 1; j < screenPriceInfo.size(); j++) {
                    Date startDate1 = TimeUtil.formatDateHH_mm(screenPriceInfo.get(j).getStartTime());
                    Date endDate1 = TimeUtil.formatDateHH_mm(screenPriceInfo.get(j).getEndTime());
                    String days1 = screenPriceInfo.get(j).getDayids();
                    // 假设选中的周天有值 需判空处理？
                    String[] daysArr1 = days1.split(",");
                    for (int x = 0; x < daysArr1.length; x++) {
                        if (dayMap != null && dayMap.get(daysArr1[x]) != null && dayMap.get(daysArr1[x])) {// 对比时间是否交叉
                            if ((startDate.before(startDate1) && endDate.after(startDate1))
                                    || (startDate.before(endDate1) && endDate.after(endDate1))
                                    || (startDate1.before(startDate) && endDate1.after(startDate))
                                    || (startDate1.before(endDate) && endDate1.after(endDate))
//                                    || startDate.equals(startDate1) || startDate.equals(endDate1)
//                                    || endDate.equals(startDate1) || endDate.equals(endDate1)
                            ) {
//										System.out.println("第"+i+"条数据与第"+j+"条数据时间交叉了 day:" +daysArr1[x] );
                                throw new DataException(DataException.Type.FAIL, "设置时间不能重叠");
                            }
                        }
                    }
                }
            }
        }
        return ResponseMessage.ok();
    }
}
